package cn.wjdiankong.toutiaovideo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.ss.android.common.applog.GlobalContext;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.wjdiankong.ijkplayer.manager.PlayerView;
import cn.wjdiankong.ijkplayer.manager.VideoijkBean;
import cn.wjdiankong.levideo.R;
import cn.wjdiankong.levideo.activity.BaseActivity;
import cn.wjdiankong.levideo.activity.ToutiaoVideoActivity;
import cn.wjdiankong.levideo.data.LevideoData;
import cn.wjdiankong.levideo.database.LocalStorage;
import cn.wjdiankong.levideo.utils.AdUtils;
import cn.wjdiankong.levideo.utils.AdUtils.AdListener;
import cn.wjdiankong.levideo.utils.Const;
import cn.wjdiankong.levideo.utils.FileUtils;
import cn.wjdiankong.levideo.utils.Logger;
import cn.wjdiankong.levideo.utils.UIUtil;
import cn.wjdiankong.levideo.utils.Utils;
import cn.wjdiankong.levideo.view.ProgressWheel;

public class DownloadActivity extends BaseActivity implements AdListener{

	private TextView resultTextView;

	private String strURL = "http://www.toutiao.com/a6361599161015468545";
	
	private final static int GETHTML_CODE = 1;
	private final static int GETVIDEOJSON_CODE = 2;
	private final static int DOWNLOADVIDEO_CODE = 3;
	
	private ProgressWheel progressView;
	private Button browserBtn;
	private String videoTitle;
	
	private PlayerView player;
	private View rootView;
	private View errorView;
	
	private String[] stepStrAry = new String[]{"正在请求页面信息", "请求页面信息成功", "请求页面信息失败", "正在请求视频数据", "请求视频数据成功", "请求视频数据失败", "视频已经存在"};
	
	public LinearLayout bannerLayout;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_toutiao_download);
		initView();
		initData();
	}
	
	@Override
	protected void initView(){
		super.initView();
		setLeftImg(R.drawable.back_icon);
		setTitle("头条视频下载");
		resultTextView = (TextView) findViewById(R.id.edthttp);
		progressView = (ProgressWheel) findViewById(R.id.progress);
		browserBtn = (Button) findViewById(R.id.browser_video_btn);
		browserBtn.setClickable(false);
		browserBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ToutiaoVideoActivity.startDefault(DownloadActivity.this);
			}
		});
		rootView = findViewById(R.id.videoplayer_view);
		errorView = findViewById(R.id.error);
		bannerLayout = (LinearLayout) findViewById(R.id.ad_banner_layout);
	}
	
	@Override
	protected void initData(){
		super.initData();
		Intent callerIntent = getIntent();
		String subject = callerIntent.getStringExtra(Intent.EXTRA_SUBJECT);
		String text = callerIntent.getStringExtra(Intent.EXTRA_TEXT);
		Logger.log("subject:"+subject+",text:"+text);
		videoTitle = formatContent(text);
		String videoUrl = ToutiaoUtils.filterVideoUrl(text);
		Logger.log("url:"+videoUrl);
		if(TextUtils.isEmpty(videoUrl)){
			resultTextView.setText("视频地址无效");
			showErrorView();
			return;
		}
		resultTextView.setText(stepStrAry[0]);
		strURL = videoUrl;
		new Thread(new GetHtmlContentRunnable()).start();
		showLoadingView();
		AdUtils.showBannerAd(bannerLayout, this);
	}
	
	public String formatContent(String str){
		try{
			return str.split("】")[0].split("【")[1];
		}catch(Exception e){
			return str;
		}
	}
	
	@Override
	protected void clickLeftImg(){
		super.clickLeftImg();
		finish();
	}
	
	private void showLoadingView(){
		progressView.setVisibility(View.VISIBLE);
		errorView.setVisibility(View.GONE);
		rootView.setVisibility(View.GONE);
		browserBtn.setClickable(false);
	}
	
	private void showPlayerView(){
		progressView.setVisibility(View.GONE);
		rootView.setVisibility(View.VISIBLE);
		errorView.setVisibility(View.GONE);
		browserBtn.setClickable(true);
	}
	
	private void showErrorView(){
		progressView.setVisibility(View.GONE);
		rootView.setVisibility(View.GONE);
		errorView.setVisibility(View.VISIBLE);
		browserBtn.setClickable(true);
	}
	
	private void saveVideoData(String videoPath){
		Bitmap bitmap = Utils.getVideoThumbnail(videoPath, 
				Utils.getDeviceWidth(this)-UIUtil.dip2px(getApplicationContext(), 20), 
				UIUtil.dip2px(getApplicationContext(), 240));
		String path = FileUtils.saveBitmap(getApplicationContext(), bitmap, System.currentTimeMillis()+".png");
		if(!TextUtils.isEmpty(path)){
			LevideoData levideoData = new LevideoData();
			levideoData.title = videoTitle;
			levideoData.videoPlayUrl = videoPath;
			levideoData.type = Const.VIDEO_TYPE_TOUTIAO;
			levideoData.createTime = System.currentTimeMillis();
			levideoData.videoDuration = Utils.getVideoDuration(videoPath)+"";
			levideoData.coverImgUrl = path;
			LocalStorage.getInstance().saveLevideoData(levideoData);
		}
	}
	
	private void playVideo(String videoPath){
		showPlayerView();
		List<VideoijkBean> list = new ArrayList<VideoijkBean>();
    	VideoijkBean bean = new VideoijkBean();
    	bean.title = videoTitle;
    	bean.url = videoPath;
    	list.add(bean);
    	player = new PlayerView(this, null);
        player.setScaleType(PlayerView.SCALETYPE_FITXY);
    	player.setTitle(videoTitle).forbidTouch(false)
    			.hideCenterPlayer(true)
    			.hideHideTopBar(true)
                .setPlaySource(list, 0)
                .startPlay();
    	rootView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				player.toggleBarView();
			}
		});
	}
	
	class GetHtmlContentRunnable implements Runnable{
		@Override
		public void run() {
			String htmlStr = ToutiaoUtils.getHtmlContent(strURL);
			Message msg = new Message();
			msg.what = GETHTML_CODE;
			msg.obj = htmlStr;
			mHandler.sendMessage(msg);
		}
	}
	
	class GetVideoJsonRunnable implements Runnable{
		
		private String url;
		public GetVideoJsonRunnable(String url){
			this.url = url;
		}
		
		@Override
		public void run() {
			String jsonStr = ToutiaoUtils.getVideoJsonData(url);
			Message msg = new Message();
			msg.what = GETVIDEOJSON_CODE;
			msg.obj = jsonStr;
			mHandler.sendMessage(msg);
		}
	}
	
	class DownloadVideoRunnable implements Runnable{
		
		private String url;
		public DownloadVideoRunnable(String url){
			this.url = url;
		}
		
		@Override
		public void run() {
			Message msg = new Message();
			msg.what = DOWNLOADVIDEO_CODE;
			//这里注意要用全局的strURL，而不能用视频的url，因为通过测试发现同一个视频的url不一样，但是全局数据的strURL是一样的
			String name = Utils.getMD5(strURL);
			String filePath = FileUtils.getSaveVideoFileName(GlobalContext.getContext(), Const.VIDEO_TYPE_TOUTIAO, name);
			File videoFile = new File(filePath);
			Logger.log("exist:"+videoFile.exists()+",path:"+videoFile.getAbsolutePath());
			if(videoFile.exists()){//文件已经存在了，不进行下载了
				msg.obj = filePath;
				msg.arg1 = 0;
			}else{
				String videoPath = ToutiaoUtils.downloadVideo(url, videoFile);
				msg.obj = videoPath;
				msg.arg1 = 1;
			}
			mHandler.sendMessage(msg);
		}
	}
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
				case GETHTML_CODE:
					resultTextView.setText(stepStrAry[0]);
					String htmlStr = (String)msg.obj;
					String jsonUrl = ToutiaoUtils.getCRC32Url(htmlStr);
					new Thread(new GetVideoJsonRunnable(jsonUrl)).start();
					break;
				case GETVIDEOJSON_CODE:
					String jsonStr = (String)msg.obj;
					if(TextUtils.isEmpty(jsonStr)){
						resultTextView.setText(stepStrAry[2]);
						showErrorView();
						return;
					}
					resultTextView.setText(stepStrAry[1]+"\n\n"+stepStrAry[3]);
					String mainUrl = ToutiaoUtils.parseJsonGetMainUrl(jsonStr);
					new Thread(new DownloadVideoRunnable(mainUrl)).start();
					break;
				case DOWNLOADVIDEO_CODE:
					String videoPath = (String)msg.obj;
					if(TextUtils.isEmpty(videoPath)){
						resultTextView.setText(stepStrAry[1]+"\n\n"+stepStrAry[5]);
						showErrorView();
						return;
					}
					if(msg.arg1 == 1){
						resultTextView.setText(stepStrAry[1]+"\n\n"+stepStrAry[4]);
						UIUtil.showShortHintToast(getApplicationContext(), "视频下载完成,设置页面进行查看");
						saveVideoData(videoPath);
					}else if(msg.arg1 == 0){
						resultTextView.setText(stepStrAry[1]+"\n\n"+stepStrAry[5]);
						UIUtil.showShortHintToast(getApplicationContext(), "文件已经存在，不进行下载直接播放");
					}
					playVideo(videoPath);
					break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
    protected void onPause() {
        super.onPause();
        if (player != null) {
            player.onPause();
        }
        muteAudioFocus(getApplicationContext(), true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (player != null) {
            player.onResume();
        }
        muteAudioFocus(getApplicationContext(), false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.onDestroy();
        }
    }

    @Override
    public void onBackPressed() {
        if (player != null && player.onBackPressed()) {
            return;
        }
        super.onBackPressed();
    }
	
	/**
     * @param bMute 值为true时为关闭背景音乐。
     */
    public static boolean muteAudioFocus(Context context, boolean bMute) {
        boolean bool = false;
        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (bMute) {
			int result = am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
            bool = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
        } else {
            int result = am.abandonAudioFocus(null);
            bool = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
        }
        return bool;
    }
    
    @Override
	protected String getPageName() {
		return "toutiao_download";
	}

	@Override
	public void showSucc() {
		
	}

	@Override
	public void showFail() {
		
	}

	@Override
	public void click() {
		
	}

	@Override
	public void close() {
		
	}

}
